package com.baturu.vin.ford.service.impl;

import com.baturu.vin.base.service.EPCCacheRealTimeProcess;
import com.baturu.vin.dto.EPCAnalyserEnum;
import com.baturu.vin.ford.dal.dao.FordCommonDAO;
import com.baturu.vin.ford.dal.dao.FordVinInfoDAO;
import com.baturu.vin.ford.util.AmfUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@SuppressWarnings("unchecked")
@Service("fordEPCCacheRealTimeProcess")
public class FordEPCCacheRealTimeProcess implements EPCCacheRealTimeProcess {

    @Autowired
    private FordCommonDAO commonDAO;

    @Autowired
    private FordVinInfoDAO vinInfoDAO;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean buildVinAnalyticalResults(String vinCode, String analyticalResults) throws Exception {
//        byte[] analyticalByteArrayContent = analyticalResults.getBytes("ISO8859-1");
//        String jsonText = AmfUtil.transformDataObject(analyticalByteArrayContent);


        JsonNode catalogNode = objectMapper.readTree(analyticalResults).get("catalog");
        if (catalogNode == null) {
            log.info("解析器【{}】缓存【{}】结果为空，该车架号可能不属于福特！", EPCAnalyserEnum.FORD.getDesc(), vinCode);
            return false;
        }

        // Vin数据入库
        Map<String, Object> vinItem = new HashMap<>();
        String catalogCode = catalogNode.get("data").asText();
        String catalogType = catalogNode.get("type").asText();

        List<Map<String, Object>> optionsForVin = Lists.newArrayList();
        //增加处理major级别的option
        Map<String, Object> majorMap = objectMapper.readValue(catalogNode.get("catalogInfoList").get(0).toString(), Map.class);
        majorMap.forEach((key, value) -> {
            if ("clientCatalogAttributes".equals(key)) {
                if (Objects.nonNull(value)) {
                    List<Map<String, Object>> majorList = (List<Map<String, Object>>) value;
                    List<Map<String, Object>> options = majorList.stream().flatMap(major -> {
                        String attributeCode = String.valueOf(major.get("data"));
                        String attributeLabel = String.valueOf(major.get("label"));
                        List<Map<String, String>> optionsVehicle = (List<Map<String, String>>) major.get("options");
                        return optionsVehicle.stream().map(attr -> {
                            String code = attr.get("data");
                            String label = attr.get("label");
                            String englishLabel = attr.get("englishLabel");
                            if (StringUtils.isBlank(code)) {
                                return null;
                            }
                            Map<String, Object> option = new HashMap<>();
                            option.put("attributeCode", attributeCode);
                            option.put("code", code);
                            option.put("label", label);
                            option.put("englishLabel", englishLabel);
                            option.put("attributeLabel", attributeLabel);
                            return option;
                        }).filter(Objects::nonNull);
                    }).collect(Collectors.toList());

                    optionsForVin.addAll(options);
                }
            }
        });


        //只处理了minor级别的option
        Map<String, Object> vehicleMap = objectMapper.readValue(catalogNode.get("vehicle").toString(), Map.class);
        vehicleMap.forEach((key, value) -> {
            if ("interpretationAVSData".equals(key)) {
                vinItem.put("interpretationAVSData", ((List<Map<String, String>>) value).stream().map(m -> m.get("type") + "|" + m.get("data")).collect(Collectors.joining(";")));
            } else if ("vehicleInfoList".equals(key)) {
                if (Objects.nonNull(value)) {
                    List<Map<String, Object>> vehicleInfoList = (List<Map<String, Object>>) value;
                    List<Map<String, Object>> options = vehicleInfoList.stream().flatMap(vehicleInfo -> {
                        String attributeCode = String.valueOf(vehicleInfo.get("data"));
                        List<Map<String, String>> clientVehicleAttributes = (List<Map<String, String>>) vehicleInfo.get("clientVehicleAttributes");
                        return clientVehicleAttributes.stream().map(attr -> {
                            String code = attr.get("data");
                            String label = attr.get("label");
                            if (StringUtils.isBlank(code)) {
                                return null;
                            }
                            Map<String, Object> option = new HashMap<>();
                            option.put("attributeCode", attributeCode);
                            option.put("code", code);
                            option.put("label", label);
                            option.put("englishLabel", "");
                            option.put("attributeLabel", "");
                            return option;
                        }).filter(Objects::nonNull);
                    }).collect(Collectors.toList());

                    optionsForVin.addAll(options);

                }
            } else if (null != value && String.class.isAssignableFrom(value.getClass())) {
                vinItem.put(key, value.toString().trim());
            } else {
                vinItem.put(key, value);
            }
        });

        if (CollectionUtils.isNotEmpty(optionsForVin)) {
            commonDAO.saveOption(optionsForVin);
        }

        vinItem.put("catalogCode", catalogCode);
        vinItem.put("catalogType", catalogType);
        vinInfoDAO.saveVin(vinItem);
        return true;
    }
}
